package com.neusoft.elm_servlet.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBUtil {
	
	//将固定输入的内容提出，声明为静态常量
	private static final String DRIVER_CLASS_NAME = "com.mysql.jdbc.Driver";
	private static final String URL = "jdbc:mysql://localhost:3306/elm?characterEncoding=utf-8";
	private static final String USER_NAME = "root";
	private static final String PASSWORLD = "root";
	
	//解决好内存泄漏问题，用于线程并发和线程隔离
	private static final ThreadLocal<Connection> TL = new ThreadLocal<>();
	
	
	/**
	 *  加载驱动并创建连接
	 * 
	 */
	public static Connection createConnection() throws SQLException {
		
		//1.加载JDBC驱动
		try {
			Class.forName(DRIVER_CLASS_NAME);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
			//2.获取连接对象
		//此处异常已向上throws 
		
//		Connection con = DriverManager.getConnection
//					(URL ,USER_NAME , PASSWORLD);
//		return con;
		//在下方合并
		return DriverManager.getConnection(URL ,USER_NAME , PASSWORLD);
		
	}
	
	public static Connection getConnection() throws SQLException {
		
		Connection con = TL.get();
		if (con == null) {
			//创建并set
			con = createConnection();
			TL.set(con);
		}
		return con;
	}
	
	/**
	 *  关闭流
	 * 
	 */
	
	public static void close(ResultSet rs,PreparedStatement ps) 
			throws SQLException{
		//此处异常已向上throws 
			if (rs != null) {
				rs.close();
			}
			if (ps != null) {
				ps.close();
			}
	}
	
	public static void close(ResultSet rs,PreparedStatement ps,Connection con) 
			throws SQLException{
		//此处异常已向上throws 
			if (rs != null) {
				rs.close();
			}
			if (ps != null) {
				ps.close();
			}
			if (con != null) {
				con.close();
				TL.remove();
			}
	}
	
	/**
	 * 单独关闭con连接
	 * @throws SQLException 
	 */
	public static void closeCon() throws SQLException{
		Connection con = TL.get();
		if (con != null) {
			con.close();
			TL.remove();
		}
	}
	
	/**
	 * 开启事务，关闭自动提交
	 * @throws SQLException 
	 */
	public static void beginTranscation() throws SQLException {
		Connection con = getConnection();
		con.setAutoCommit(false);
	}
	
	/**
	 * 提交
	 */
	public static void commit() throws SQLException {
		Connection con = getConnection();
		con.commit();
	}
	
	/**
	 * 回滚
	 */
	public static void rollback() throws SQLException {
		Connection con = getConnection();
		con.rollback();
	}
	
	
	
}
